package cn.edu.lingnan.controllerV1;

import cn.edu.lingnan.constant;
import cn.edu.lingnan.service.QuestionStoreService;
import cn.edu.lingnan.service.QuestionsService;
import cn.edu.lingnan.user.dtos.Result;
import cn.edu.lingnan.user.vos.QuestionBankVO;
import cn.edu.lingnan.user.vos.QuestionVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/questions_details")
public class QuestionsController {

    private static final Logger log = LoggerFactory.getLogger(QuestionsController.class);
    @Autowired
    private QuestionsService questionsService;

    /**
     * 根据 storeId 查询题库的所有题目及选项，返回树形结构
     *
     * @param storeId 题库ID
     * @return ResponseEntity 包含 QuestionBankVO 的响应实体
     */
    @GetMapping("/tree")
    public Result<?> getQuestionStoreTree(@RequestParam(value = "storeId") Integer storeId) {
        if (storeId == null) {
            return Result.error(constant.STORE_ID_NULL_ERROR);
        }

        QuestionBankVO storeTree = questionsService.getQuestionStoreTree(storeId);
        if (storeTree == null) {
            return Result.error(constant.QUESTION_STORE_NOT_FOUND_ERROR);
        }

        return Result.success(storeTree);
    }
//    根据题目id查询题目详情
    @GetMapping("/questionDetailById")
    public Result<QuestionVO> getQuestionDetailById(@RequestParam("questionId") Integer questionId) {
        if (questionId == null) {
            return Result.error(constant.QUESTION_ID_NULL_MSG);
        }

        return Result.success(questionsService.getQuestionDetailById(questionId));
    }
    //修改题目
    @PostMapping("/updateQuestionById")
    public Result<Boolean> updateQuestionById(@RequestBody QuestionVO questionVO,@RequestParam("questionId") Integer questionId) {
        log.info("questionId:{}",questionId);
        log.info("questionVO:{}",questionVO);
        questionsService.updateQuestionById(questionVO,questionId);
        return Result.success();
    }
    //添加题目
    @PostMapping("/addQuestion")
    public Result<Boolean> addQuestion(@RequestBody QuestionVO questionVO) {

        questionsService.addQuestion( questionVO);
        return Result.success();
    }
    //根据题库id删除题目，数据表设计了级联删除，直接删题目表即可
    @DeleteMapping("/deleteQuestionById")
    public Result<Boolean> deleteQuestionById(@RequestParam("questionId") Integer questionId) {
        if (questionId == null) {
            return Result.error("题目ID不能为空");
        }
        log.info("questionId:{}",questionId);
        Boolean flag = questionsService.deleteQuestionById(questionId);
        if (flag){
            return Result.success();
        }
         return Result.error("删除失败,试题关联了试卷");
    }

}
